package com.sun.designpatternsdemo.prototype.bean

import android.util.Log
import java.util.*

/**
 * 版权：xx公司 版权所有
 * @author sun
 * 版本：1.0
 * 创建日期：2021/7/1 13:34
 * 描述：实体类
 * * 1. 创建一个实现了 Cloneable 接口的抽象类。
 */
abstract class Shape : Cloneable {
    var id: String? = null
    var type: String? = null

    abstract fun draw()

    public override fun clone(): Any {
        var obj: Any? = null
        try {
            obj = super.clone()
        } catch (e: CloneNotSupportedException) {
            e.message?.let { Log.e("--", it) }
        }
        return obj!!
    }
}

//2. 创建扩展了上面抽象类的实体类。Circle 圆形
class Circle : Shape() {
    init {
        type = "Circle"
    }

    override fun draw() {
        Log.e("---", "Inside Circle::draw() method.")
    }
}

// 创建扩展了上面抽象类的实体类。Rectangle 矩形
class Rectangle : Shape() {
    init {
        type = "Rectangle"
    }

    override fun draw() {
        Log.e("---", "Inside Rectangle::draw() method.")
    }
}

//创建扩展了上面抽象类的实体类。Square 正方形
class Square : Shape() {
    init {
        type = "Square"
    }

    override fun draw() {
        Log.e("---", "Inside Square::draw() method.")
    }
}

//创建一个类，从数据库获取实体类，并把它们存储在一个 Hashtable 中。
class ShapeCache {
    companion object {
        private val shapeMap = Hashtable<String, Shape>()

        fun getShape(shapeId: String): Shape {
            val shape = shapeMap[shapeId]
            return shape?.clone() as Shape
        }

        // 对每种形状都运行数据库查询，并创建该形状
        // shapeMap.put(shapeKey, shape);
        // 例如，我们要添加三种形状
        fun loadCache() {
            val circle = Circle()
            circle.id = "1"
            shapeMap[circle.id] = circle

            val rectangle = Rectangle()
            rectangle.id = "2"
            shapeMap[rectangle.id] = rectangle

            val square = Square()
            square.id = "3"
            shapeMap[square.id] = square
        }
    }
}